/**
 * @description 路由拦截状态管理，目前两种模式：all模式与intelligence模式，其中partialRoutes是菜单暂未使用
 */
import { defineStore } from 'pinia'
import { local } from '@/utils/storage'
import { NButton } from 'naive-ui'
import type { appState, userinfoType } from '@/types/stores/app'
import loginApi from '@/service/api/login'
import { setLocale } from '@/utils/i18n'
import logApi from '@/service/api/log'
import router from '@/router'

export const useAppsStore = defineStore('app', {
  state: (): appState => ({
    loginShow: false,
    token: '',
    userInfo: {},
    lang: local.get('lang') || 'zhCN'
  }),
  getters: {
    getLoginShow: state => state.loginShow,
    getLang: state => state.lang,
    getToken: state => state.token,
    getLoginStatus: state => !!state.userInfo?.id,
    getUserInfo: state => state.userInfo as userinfoType
  },
  actions: {
    setLoginShow(status: boolean) {
      this.loginShow = status
    },
    setAppLang(lang: App.lang) {
      setLocale(lang)
      local.set('lang', lang)
      this.lang = lang
    },
    /**
     * @description 获取用户信息
     * @returns data
     */
    async doUserInfo(): Promise<userinfoType> {
      const { code, data, msg } = await loginApi.doInfo()
      if (code !== 0) {
        this.signOut()
        throw msg
      }
      this.userInfo = data
      return data
    },
    async logNotice() {
      try {
        const { data } = await logApi.newLog()
        if (data && data?.id) {
          let text = `${data.info.name}[${data.menu.name}`
          if (data.menu.remark) {
            text += `:${data.menu.remark}`
          }
          text += ']'
          const noticeBl = msgUtil.$notification.create({
            title: '上次浏览记录',
            content: () => {
              return h(
                'div',
                {
                  style: {
                    display: 'flex',
                    'align-items': 'center',
                    cursor: 'pointer'
                  },
                  onClick: () => {
                    noticeBl?.destroy()
                    router.push({
                      path: '/mhdetail',
                      query: {
                        id: data.info.id
                      }
                    })
                  }
                },
                text
              )
            },
            action: () =>
              h(
                NButton,
                {
                  text: true,
                  type: 'primary',
                  onClick: () => {
                    noticeBl?.destroy()
                    router.push({
                      path: '/mhdetail',
                      query: {
                        id: data.info.id
                      }
                    })
                  }
                },
                {
                  default: () => '继续查看'
                }
              ),
            duration: 10000
          })
        }
      } catch (error: any) {
        console.log(error)
      }
    },
    /**
     * @description 设置token，并且获取用户信息
     * @param token
     * @returns
     */
    async setToken(token: string) {
      local.set(import.meta.env.VITE_TOKEN_LOCATION_NAME, token)
      this.token = token
      const res = await this.doUserInfo()
      this.logNotice()
      return res
    },
    /**
     * @description 登出
     * */
    signOut() {
      local.remove(import.meta.env.VITE_TOKEN_LOCATION_NAME)
      this.token = ''
      this.userInfo = {}
    }
  }
})
